import { showToast } from "vant";
// 图片下载
export const downloadImg = (imgUrl,imgName) => {
  fetch(imgUrl)
  .then(response => {
    if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
    return response.blob();
  })
  .then(blob => {
    // 创建下载链接
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${imgName}.png`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    // 显示成功Toast
    showToast('Download completed', 'success');
  })
  .catch(error => {
    console.error('下载失败:', error);
    showToast(`Download failed: ${error.message}`, 'error');
  });
}

export const downloadCrossOriginImage = async (imageUrl) => {
  try {
    const response = await fetch(imageUrl, {
      mode: 'cors' // 必须启用 CORS
    })
    if (!response.ok) throw new Error('network error')

    const blob = await response.blob()
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    //link.download = 'custom-name.jpg' // 自定义文件名
    document.body.appendChild(link)
    link.click()
    URL.revokeObjectURL(link.href)
  } catch (error) {
    console.error('下载失败:', error)
  }
}